package com.bezdelnick.forum.repository;

import com.bezdelnick.forum.util.PropertyUtils;
import com.bezdelnick.forum.web.ForumApplication;
import com.bezdelnick.forum.web.resource.ImageFromFileSystemReference;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.request.mapper.ResourceMapper;
import org.apache.wicket.request.resource.ResourceReference;
import org.apache.wicket.util.file.File;
import org.apache.wicket.util.file.Files;
import org.apache.wicket.util.file.Folder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Properties;

/**
 * Created by IntelliJ IDEA.
 * User: Bezdelnick
 * Date: 06.09.12
 * Time: 10:19
 * To change this template use File | Settings | File Templates.
 */
public class FileSystemFolderRepository {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileSystemFolderRepository.class);

    private static FileSystemFolderRepository instance = null;
    private static final String IMAGE_RESOURCE_PREFIX = "wicket_img_";
    private String location;
    private String mountResourcePath = "/files/images/";

    private ResourceReference reference;

    private FileSystemFolderRepository() {
        //
    }

    public static FileSystemFolderRepository get() {
        if (instance == null)
            instance = new FileSystemFolderRepository();
        return instance;
    }

    public String getMountResourcePath() {
        return mountResourcePath;
    }

    public void addFile(FileUpload upload) {
        File newFile = new File(getRepositoryLocation(), upload.getClientFileName());
        checkFileExists(newFile);
        try {
            newFile.createNewFile();
            upload.writeTo(newFile);
            LOGGER.info("Saved file: " + upload.getClientFileName());
            if (mountResource(newFile))
                LOGGER.info("File reference is created successful!!");
        } catch (Exception e) {
            LOGGER.warn("Unable to write file");
            LOGGER.warn(e.getMessage());
        }
    }

    public boolean mountResource(final File file) {
        try {
            ForumApplication.get().mount(new ResourceMapper(
                    mountResourcePath + file.getName(),
                    new ImageFromFileSystemReference(file.getName(), file.getAbsolutePath()))
            );
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public boolean mountAllResources() {
        try {
            File[] files = new Folder(getRepositoryLocation()).getFiles();
            for (File file : files) {
                ForumApplication.get().mount(new ResourceMapper(
                        mountResourcePath + file.getName(),
                        new ImageFromFileSystemReference(file.getName(), file.getAbsolutePath()))
                );
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public String getFileUrlByFileName(String fileName) {
        return getMountResourcePath() + fileName;
    }

    private void checkFileExists(File newFile) {
        if (newFile.exists()) {
            if (!Files.remove(newFile)) {
                throw new IllegalStateException("Unable to overwrite " + newFile.getAbsolutePath());
            }
        }
    }

    public String getRepositoryLocation() {
        Properties properties = PropertyUtils.loadFromClassPath("repositories.properties", false);
        return properties.getProperty("filesystem.folder.repository.location");
    }
}
